package js.web.center.netty.channel;

import org.apache.log4j.Logger;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import js.web.center.core.config.JsWebConfig;
import js.web.center.netty.entity.JsWebSocketBaseProtocol;
import js.web.center.netty.net.JsWebNetApi;
import js.web.center.script.core.JsWebScriptEngineCore;
/**
 * 消息解析通道
 * @author qpduw
 *
 */
@Sharable
public class JsWebSocketHandler extends ChannelInboundHandlerAdapter {
	private static Logger logger=Logger.getLogger(JsWebSocketHandler.class);
	private static JsWebScriptEngineCore jsWebScriptEngineCore=null; 
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		JsWebSocketBaseProtocol baseProtocol=(JsWebSocketBaseProtocol) msg;
		if(jsWebScriptEngineCore==null){
			try{
				jsWebScriptEngineCore=new JsWebScriptEngineCore();
				jsWebScriptEngineCore.init("web/JsSocket");
				jsWebScriptEngineCore.init(JsWebConfig.LIBS_BASE);
				jsWebScriptEngineCore.appParams(JsWebConfig.SELF, this);
				jsWebScriptEngineCore.appParams(JsWebConfig.PARENT, jsWebScriptEngineCore);
			}catch(Exception e){
				logger.error("JsWebSocketHandler ERROR:{}",e);
			}
		}
		JsWebNetApi.updateChannelHandler(ctx);
		try{
			String info=new String(baseProtocol.getContent());
			jsWebScriptEngineCore.function("handler", ctx,info);
		}catch(Exception e){
			logger.error("JsWebSocketHandler ERROR:{}",e);
		}
	}
	/**
	 * 调试打印日志
	 * @param object
	 */
	public void log(Object object){
		logger.info(object);
	}
	/**
	 * 发送字符串到客户端
	 * @param ctx
	 * @param info
	 */
	public void send(ChannelHandlerContext ctx,Object info){
		byte[] bytes = info.toString().getBytes();
		JsWebSocketBaseProtocol baseProtocol=new JsWebSocketBaseProtocol(bytes.length, bytes);
		ctx.writeAndFlush(baseProtocol);
	}
	/**
	 * 发送消息
	 * @param ctx
	 * @param bytes
	 */
	public void send(ChannelHandlerContext ctx,byte[] bytes){
		JsWebSocketBaseProtocol baseProtocol=new JsWebSocketBaseProtocol(bytes.length, bytes);
		ctx.writeAndFlush(baseProtocol);
	}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		super.channelRegistered(ctx);
	}
	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		JsWebNetApi.removeChannelHandler(ctx);
		if(jsWebScriptEngineCore!=null){
			try{
				jsWebScriptEngineCore.function("disconnect", ctx);
			}catch(Exception e){
				logger.error("JsWebSocketHandler ERROR:{}",e);
			}
		}
		super.channelUnregistered(ctx);
	}
}